<?php

namespace app\admin\library;

use app\admin\model\Admin;
use app\admin\model\yxerp\AdminPermission;
use app\admin\model\yxerp\DepartmentPermission;
use app\admin\model\yxerp\Employee;
use app\admin\model\yxerp\EmployeePermission;
use app\admin\model\yxerp\Permission;
use app\admin\model\yxerp\PositionPermission;
use think\facade\Db;
use think\facade\Config;
use think\facade\Session;

/**
 * YXERP权限服务类
 */
class YxerpAuth
{
    /**
     * 当前登录用户
     * @var object
     */
    protected $user = null;
    
    /**
     * 当前用户ID
     * @var int
     */
    protected $userId = 0;
    
    /**
     * 当前用户关联的员工信息
     * @var object
     */
    protected $employee = null;
    
    /**
     * 员工ID
     * @var int
     */
    protected $employeeId = 0;
    
    /**
     * 部门ID
     * @var int
     */
    protected $departmentId = 0;
    
    /**
     * 岗位ID
     * @var int
     */
    protected $positionId = 0;
    
    /**
     * 是否YXERP插件管理员
     * @var bool
     */
    protected $isYxerpAdmin = false;
    
    /**
     * 构造函数
     */
    public function __construct()
    {
        // 如果已经登录，则获取当前登录用户信息
        if ($uid = Session::get('admin.id')) {
            $this->user = Admin::find($uid);
            $this->userId = $uid;
            
            // 获取关联的员工信息
            $this->employee = Employee::where('admin_id', $this->userId)->find();
            
            if ($this->employee) {
                $this->employeeId = $this->employee->id;
                $this->departmentId = $this->employee->department_id;
                $this->positionId = $this->employee->position_id;
            }
            
            // 检查是否为YXERP插件管理员
            $adminPermission = AdminPermission::where('admin_id', $this->userId)->find();
            $this->isYxerpAdmin = !empty($adminPermission);
        }
    }
    
    /**
     * 检查权限
     * @param string $permissionCode 权限代码
     * @return bool
     */
    public function check($permissionCode)
    {
        // 如果是超级管理员角色，直接放行
        if ($this->checkSuperAdmin()) {
            return true;
        }
        
        // 如果是YXERP插件管理员，直接放行
        if ($this->isYxerpAdmin) {
            return true;
        }
        
        // 获取权限信息
        $permission = Permission::where('code', $permissionCode)->where('status', 1)->find();
        if (!$permission) {
            return false;
        }
        
        // 如果没有关联到员工，则没有任何权限
        if (!$this->employee) {
            return false;
        }
        
        // 检查个人权限 - 优先级最高
        $hasPersonalPermission = EmployeePermission::where('employee_id', $this->employeeId)
            ->where('permission_id', $permission->id)
            ->find();
            
        if ($hasPersonalPermission) {
            return true;
        }
        
        // 检查岗位权限
        if ($this->positionId) {
            $hasPositionPermission = PositionPermission::where('position_id', $this->positionId)
                ->where('permission_id', $permission->id)
                ->find();
                
            if ($hasPositionPermission) {
                return true;
            }
        }
        
        // 检查部门权限
        if ($this->departmentId) {
            $hasDepartmentPermission = DepartmentPermission::where('department_id', $this->departmentId)
                ->where('permission_id', $permission->id)
                ->find();
                
            if ($hasDepartmentPermission) {
                return true;
            }
        }
        
        // 所有检查都未通过，则没有权限
        return false;
    }
    
    /**
     * 检查数据权限范围
     * @param string $permissionCode 权限代码
     * @return string|null 返回数据权限类型
     */
    public function checkDataScope($permissionCode)
    {
        // 如果是超级管理员角色，返回全部数据权限
        if ($this->checkSuperAdmin()) {
            return Permission::DATA_SCOPE_ALL;
        }
        
        // 如果是YXERP插件管理员，返回全部数据权限
        if ($this->isYxerpAdmin) {
            return Permission::DATA_SCOPE_ALL;
        }
        
        // 获取权限信息
        $permission = Permission::where('code', $permissionCode)->where('status', 1)->find();
        if (!$permission) {
            return null;
        }
        
        // 如果没有关联到员工，则没有任何数据权限
        if (!$this->employee) {
            return null;
        }
        
        // 检查个人数据权限 - 优先级最高
        $employeePermission = EmployeePermission::where('employee_id', $this->employeeId)
            ->where('permission_id', $permission->id)
            ->find();
            
        if ($employeePermission) {
            return $employeePermission->data_scope;
        }
        
        // 检查岗位数据权限
        if ($this->positionId) {
            $positionPermission = PositionPermission::where('position_id', $this->positionId)
                ->where('permission_id', $permission->id)
                ->find();
                
            if ($positionPermission) {
                return $positionPermission->data_scope;
            }
        }
        
        // 检查部门数据权限
        if ($this->departmentId) {
            $departmentPermission = DepartmentPermission::where('department_id', $this->departmentId)
                ->where('permission_id', $permission->id)
                ->find();
                
            if ($departmentPermission) {
                return $departmentPermission->data_scope;
            }
        }
        
        // 所有检查都未通过，则没有数据权限
        return null;
    }
    
    /**
     * 检查是否为系统超级管理员
     * @return bool
     */
    protected function checkSuperAdmin()
    {
        // 获取当前用户的角色组
        $groupIds = Db::name('admin_group_access')
            ->where('uid', $this->userId)
            ->column('group_id');
            
        // 检查是否有超级管理员角色
        $superAdminId = Config::get('buildadmin.super_admin_group_id', 1);
        return in_array($superAdminId, $groupIds);
    }
    
    /**
     * 获取数据过滤条件（根据数据权限构建查询条件）
     * @param string $permissionCode 权限代码
     * @param string $tableAlias 表别名
     * @return array 查询条件数组
     */
    public function getDataFilter($permissionCode, $tableAlias = '')
    {
        $prefix = $tableAlias ? $tableAlias . '.' : '';
        
        // 获取数据权限范围
        $dataScope = $this->checkDataScope($permissionCode);
        
        // 如果没有数据权限或是全部数据权限，则不需要过滤
        if (!$dataScope || $dataScope == Permission::DATA_SCOPE_ALL) {
            return [];
        }
        
        // 构建查询条件
        switch ($dataScope) {
            case Permission::DATA_SCOPE_DEPT:
                // 获取当前部门及其所有子部门ID
                $deptIds = $this->getChildDepartmentIds($this->departmentId);
                $deptIds[] = $this->departmentId;
                return [[$prefix . 'department_id', 'in', $deptIds]];
                
            case Permission::DATA_SCOPE_POSITION:
                // 只能查看本岗位数据
                return [[$prefix . 'position_id', '=', $this->positionId]];
                
            case Permission::DATA_SCOPE_SELF:
                // 只能查看个人数据
                return [[$prefix . 'employee_id', '=', $this->employeeId]];
                
            default:
                return [];
        }
    }
    
    /**
     * 获取所有子部门ID
     * @param int $departmentId 部门ID
     * @return array 子部门ID数组
     */
    protected function getChildDepartmentIds($departmentId)
    {
        $childIds = [];
        
        $children = Db::name('yxerp_department')
            ->where('pid', $departmentId)
            ->field('id')
            ->select()
            ->toArray();
            
        foreach ($children as $child) {
            $childIds[] = $child['id'];
            $childIds = array_merge($childIds, $this->getChildDepartmentIds($child['id']));
        }
        
        return $childIds;
    }
} 